package com.estar.assistsurvy.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.estar.assistsurvy.R;
import com.estar.assistsurvy.activity.CetificationActivity;
import com.estar.assistsurvy.activity.HistoryActivity;
import com.estar.assistsurvy.activity.MessagesActivity;
import com.estar.assistsurvy.activity.RoborderActivity;
import com.estar.assistsurvy.activity.ShareActivity;
import com.estar.assistsurvy.activity.TaskSuperviseActivity;
import com.estar.assistsurvy.activity.app.AssistSurvyApp;
import com.estar.assistsurvy.adapter.HomePageGridviewAdapter;
import com.estar.assistsurvy.entity.Item;
import com.estar.assistsurvy.entity.MessageList;
import com.estar.assistsurvy.entity.RequestGetMessage;
import com.estar.assistsurvy.entity.ResponseQueryMessage;
import com.estar.assistsurvy.thread.GetMessageListThread;
import com.estar.assistsurvy.utils.MightypleUtil;
import com.estar.assistsurvy.widget.NotScrollGridView;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class HomePageFragment extends BaseFragment implements OnItemClickListener,OnPageChangeListener {

	private ViewPager homePage_vp;
	private ArrayList<ImageView> views;
	private LinearLayout pointContainer;
	private int[] res=new int[]{R.drawable.homepage};
	private ArrayList<Object> list;
	private ArrayList<ImageView> imgs=new ArrayList<ImageView>();

	private int currentItem=0;
	private Timer timer;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;
				
			case 0:
				ResponseQueryMessage queryMessage=new ResponseQueryMessage();
				queryMessage=(ResponseQueryMessage) msg.obj;
				if(queryMessage.getCode().equals("1")){
					messageList=null;
					messageList=queryMessage.getMessageList();
					getNotReadNum();
				}
//				showShortToast(queryMessage.getMessages());
				break;
				
			case 1:
				homePage_vp.setCurrentItem(currentItem);
				break;

			default:
				break;
			}
			
		};
	};
	private Intent intent;
	private HomePageGridviewAdapter gvAdapter;
	private NotScrollGridView homePage_gv;
	private String[] txts=new String[]{"抢单","任务监管","历史任务","查勘人认证","平台信使","在线客服","邀请分享"};
	private int[] res2=new int[]{R.drawable.icon_home_01,R.drawable.icon_home_02,R.drawable.icon_home_03,
			R.drawable.icon_home_04,R.drawable.icon_home_05,R.drawable.icon_home_07,R.drawable.icon_home_08};
	private String uuid,deviceId,type,receiveDate,phoneNumber;
	private SharedPreferences preferences;
	private List<MessageList> messageList;
//	private int notRead=0;
	private String roleCode,authenState,dataSources;
	private SharedPreferences prefer;
	
	@SuppressLint("InflateParams") @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(view==null){
			view=inflater.inflate(R.layout.fragment_homepage,null);
			
		}
		init();
		return view;	
	}
	
	@Override
	public void onStart() {
		// TODO Auto-generated method stub

		initView();
		getImages();
		setScrollPicture();
//		loadingDialog = new LoadingFragmentDialog();
		if(timer==null){
			timer=new Timer();
			timer.schedule(new MyTimerTask(), 0, 2000);
		}
		
		super.onStart();
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		pointContainer.removeAllViews();
		super.onPause();
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if(timer!=null){
			timer.cancel();
		}
		
		super.onDestroy();
	}
	
	private void clearState(){
		for(int i=0;i<views.size();i++){
			views.get(i).setImageResource(R.drawable.image_indicator);
		}
	}
	
	private class MyTimerTask extends TimerTask{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			currentItem++;
			if (currentItem > imgs.size() - 1) {
				currentItem = 0;
			}
			handler.sendEmptyMessage(1);
		}
		
	}
	
	private void setScrollPicture(){
		if(list.size()==0){
			ImageView img=new ImageView(getActivity());
			img.setImageResource(R.drawable.homepage);
			img.setScaleType(ImageView.ScaleType.FIT_XY);
			imgs.add(img);
		}else{
			imgs.clear();
			for (int i = 0; i < list.size(); i++) {
				ImageView img = new ImageView(getActivity());
				img.setImageResource( res[i]);
				img.setScaleType(ImageView.ScaleType.FIT_XY);
				imgs.add(img);
			}
		}
		
		//ViewPeger适配器
				homePage_vp.setAdapter(new PagerAdapter() {
					@Override
					public boolean isViewFromObject(View arg0, Object arg1) {
						return arg0 == arg1;
					}

					@Override
					public int getCount() {
						return imgs.size();
					}

					public void destroyItem(ViewGroup container, int position,
							Object object) {
						((ViewPager) container).removeView(imgs.get(position));
					}

					@Override
					public Object instantiateItem(ViewGroup container, final int position) {
						ImageView view = imgs.get(position);
						((ViewPager) container).addView(view);
						//为当前图片设置点击监听
						
						return view;
					}
				});
	}
	
	private void init(){
		homePage_gv=find(R.id.homePage_gv);
		homePage_vp=find(R.id.homePage_vp);
		pointContainer=find(R.id.pointContainer);
		
		views=new ArrayList<>();
		for(int i=0;i<res.length;i++){
			ImageView imageview=new ImageView(getActivity());
			pointContainer.addView(imageview);
			views.add(imageview);
		}
	}
	
	private void initView(){
		prefer=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
		authenState=prefer.getString("authenticationState", "");
		dataSources=prefer.getString("dataSources", "");
		phoneNumber=prefer.getString("phoneNumber", "");
		homePage_vp.setAdapter(new PagerAdapter() {

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return imgs.size();
			}

			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object) {
				// TODO Auto-generated method stub
				((ViewPager) container).removeView(imgs.get(position));
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				// TODO Auto-generated method stub
				ImageView view = imgs.get(position);
				((ViewPager) container).addView(view);
				return view;
			}

		});
		
		homePage_vp.addOnPageChangeListener(this);


		gvAdapter=new HomePageGridviewAdapter(getItems(), getActivity());
		homePage_gv.setAdapter(gvAdapter);
		homePage_gv.setOnItemClickListener(this);
		
		//获取平台信使消息列表，用于统计未读消息条数进行展示
		preferences=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
		uuid=preferences.getString("uuid", "");
		deviceId=MightypleUtil.getDeviceId(getActivity());
		type="";
		receiveDate="";
//		RequestGetMessage getMessage=new RequestGetMessage(deviceId, uuid, type, receiveDate);
//		new GetMessageListThread(getActivity(), handler, getMessage).start();
		getNotReadNum();
	}
	private SharedPreferences share;
	private void getNotReadNum(){
//		int notRead=0;
//		if(messageList!=null&&messageList.size()>0){
//			for(int i=0;i<messageList.size();i++){
//				MessageList message=new MessageList();
//				message=messageList.get(i);
//				if(message.getIsRead().equals("0")){
//					notRead++;
//				}
//			}
			share=getActivity().getSharedPreferences(phoneNumber, Context.MODE_PRIVATE);
			int i=share.getInt("number", 0);
			Log.i("nf", "首页推送消息数目---->"+i);
			gvAdapter.setGvItem(i);
//			gvAdapter.setGvItem(notRead);
			gvAdapter.notifyDataSetChanged();
//		}
	}
	
	private ArrayList<Item> getItems(){
		ArrayList<Item> items=new ArrayList<Item>();
		for(int i=0;i<txts.length;i++){
			Item item=new Item();
			item.setImg(res2[i]);
			item.setText(txts[i]);
			items.add(item);
		}
		return items;
	}

	private void getImages(){
		list=new ArrayList<Object>();
		for(int i=0;i<res.length;i++){
			list.add(res[i]);
		}
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		
			switch (position) {
			case 0:
				if(authenState.equals("0")){
					if(dataSources.equals("0")){
						setDialog();
					}else if(dataSources.equals("1")){
						showShortToast("您还未认证，请联系后台管理员进行认证操作!");
					}
					
				}else if(authenState.equals("1")){
					prefer=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE);
					roleCode=prefer.getString("rolecode", "");
					if(roleCode.equals("6")){
						showShortToast("您无此权限进入该功能!");
					}else{
						intent=new Intent(getActivity(), RoborderActivity.class);
						startActivity(intent);
					}
				}
				
				break;
				
			case 1:
				if(authenState.equals("0")){
					if(dataSources.equals("0")){
						setDialog();
					}else if(dataSources.equals("1")){
						showShortToast("您还未认证，请联系后台管理员进行认证操作!");
					}
				}else if(authenState.equals("1")){
					prefer=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE);
					roleCode=prefer.getString("rolecode", "");
					if(roleCode.equals("6")){
						intent=new Intent(getActivity(), TaskSuperviseActivity.class);
						startActivity(intent);
					}else{
						showShortToast("您无此权限进入该功能!");
					}
				}
				
				break;
				
			case 2:
//				showShortToast("后台维护中，稍后开启");

				if(authenState.equals("0")){
					if(dataSources.equals("0")){
						setDialog();
					}else if(dataSources.equals("1")){
						showShortToast("您还未认证，请联系后台管理员进行认证操作!");
					}
				}else if(authenState.equals("1")){
					
					prefer=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE);
					roleCode=prefer.getString("rolecode", "");
					if(roleCode.equals("6")){
						showShortToast("您无此权限进入该功能!");
					}else{
						intent=new Intent(getActivity(), HistoryActivity.class);
						startActivity(intent);
					}
				}
				
				break;

			case 3:
				if(authenState.equals("1")){
					prefer=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE);
					roleCode=prefer.getString("rolecode", "");
					if(roleCode.equals("6")){
						showShortToast("您无此权限进入该功能!");
					}else{
						intent=new Intent(getActivity(), CetificationActivity.class);
						startActivity(intent);
					}
				}else if(authenState.equals("0")){
					if(dataSources.equals("0")){
						setDialog();
					}else if(dataSources.equals("1")){
						showShortToast("您还未认证，请联系后台管理员进行认证操作!");
					}
				}
				
				
				break;
				
			case 4:
				if(authenState.equals("0")){
					if(dataSources.equals("0")){
						setDialog();
					}else if(dataSources.equals("1")){
						showShortToast("您还未认证，请联系后台管理员进行认证操作!");
					}
				}else if(authenState.equals("1")){
					share=getActivity().getSharedPreferences(phoneNumber, Context.MODE_PRIVATE);
					share.edit().clear().commit();
					intent=new Intent(getActivity(), MessagesActivity.class);
					startActivity(intent);
				}
				
				break;
				
			case 5:
				showShortToast("客服功能正在开发中…");
				//判断版本若为6.0申请权限
//                if(Build.VERSION.SDK_INT < 23) {
//                	initChat();
//                }else {
//                    //6.0
//                    if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
//                        //该权限已经有了
//                    	initChat();
//                    }else {
//                        //申请该权限
//                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_PHONE_STATE}, 0x1111);
//                    }
//                }
				break;
				
			case 6:
				intent=new Intent(getActivity(), ShareActivity.class);
				startActivity(intent);
				break;
				
			default:
				break;
			}
			
	}
	
//	private void initChat() {
//        if(!NetUtils.hasDataConnection(getActivity())) {
//            Toast.makeText(getActivity(), "当前没有网络连接", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        loadingDialog.show(getActivity().getFragmentManager(), "");
//        if (AssistSurvyApp.isKFSDK) {
//            loadingDialog.dismiss();
//            getPeers();
//        } else {
//            startKFService();
//        }
//    }
	
//	private LoadingFragmentDialog loadingDialog;
//    private String action,accessid,username,userid;
////    private SharedPreferences preferences;
//	private void getPeers() {
//        IMChatManager.getInstance().getPeers(new GetPeersListener() {
//            @Override
//            public void onSuccess(List<Peer> peers) {
//                if (peers.size() > 1) {
//                    PeerDialog dialog = new PeerDialog();
//                    Bundle b = new Bundle();
//                    b.putSerializable("Peers", (Serializable) peers);
//                    b.putString("type", "init");
//                    dialog.setArguments(b);
//                    dialog.show(getActivity().getFragmentManager(), "");
//
//                } else if (peers.size() == 1) {
//                    startChatActivity(peers.get(0).getId());
//                } else {
//                    startChatActivity("");
//                }
//            }
//
//            @Override
//            public void onFailed() {
//
//            }
//        });
//    }

//    private void startKFService() {
//
//        new Thread() {
//            @Override
//            public void run() {
//                IMChatManager.getInstance().setOnInitListener(new InitListener() {
//                    @Override
//                    public void oninitSuccess() {
//                    	AssistSurvyApp.isKFSDK = true;
//                        loadingDialog.dismiss();
//                        getPeers();
//                        Log.d("AssistSurvyApp", "sdk初始化成功");
//
//                    }
//
//                    @Override
//                    public void onInitFailed() {
//                    	AssistSurvyApp.isKFSDK = false;
//                        loadingDialog.dismiss();
//                        Toast.makeText(getActivity(), "客服初始化失败,请填写正确的accessid", Toast.LENGTH_SHORT).show();
//                        Log.d("AssistSurvyApp", "sdk初始化失败,请填写正确的accessid");
//                    }
//                });
//
//                //初始化IMSdk,填入相关参数
////        		preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
//        		
//                action="action";
//                accessid="af147870-fd55-11e5-981b-5966a108e974";
//                username="人人勘-"+preferences.getString("phoneNumber", "");
//                userid=preferences.getString("phoneNumber", "");
//                IMChatManager.getInstance().init(AssistSurvyApp.getInstance(), action, accessid, username, userid);
//
//            }
//        }.start();

//    }

//    private void startChatActivity(String peerId) {
//        Intent chatIntent = new Intent(getActivity(), ChatActivity.class);
//        chatIntent.putExtra("PeerId", peerId);
//        startActivity(chatIntent);
//    }


    @SuppressLint("Override")
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 0x1111:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    init();
                } else {

                }
                break;
        }
    }
	

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		clearState();
		views.get(position).setImageResource(R.drawable.image_indicator_focus);
		
	}
	
	private void setDialog(){
		new AlertDialog.Builder(getActivity(), AlertDialog.THEME_HOLO_LIGHT)
		.setMessage("您还未认证，是否前往认证？")
		.setPositiveButton("是", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				intent=new Intent(getActivity(), CetificationActivity.class);
				startActivity(intent);
			}
		})
		.setNegativeButton("否", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		})
		.create()
		.show();
	}

}
